/**
 * Ext JS Extension Library 4.0
 * Copyright(c) 2011, Cristian Constantin
 *
 */

Ext.define('Ext.ux.Ajax', {

    singleton: true,

    defaultAjaxRequestCallback: function(options, success, response) {
        if (success) {
            if (options.mask && options.mask.autoHide) {
                options.mask.hide();
            }

            if (response && response.responseText) {
                var result = Ext.decode(response.responseText);

                var message = null;

                if (result.success !== false) {
                    if (!options.silent) {
                        if (result.messages && result.messages.length > 0) {
                            message = result.messages[0];
                        }
                        else if (result.message) {
                            message = result.message;
                        }

                        if (message) {
                            if (options.quickMessage) {
                                Asdp.QuickMessageBox.show(message, options.messageTarget);
                            }
                            else {
                                Ext.Msg.show({
                                    title: this.title,
                                    icon: Ext.MessageBox.INFO,
                                    msg: message,
                                    buttons: Ext.MessageBox.OK
                                });
                            }
                        }
                    }

                    Ext.callback(options._success, options.scope, [ result, options ]);
                    Ext.callback(options._callback, options.scope, [ true, result, options ]);
                }
                else {
                    if (!options.silent || options.showErrorMessages) {
                        var messages;

                        if (result.errorsMessages) {
                            messages = result.errorsMessages;
                        }
                        else if (result.message) {
                            messages = [result.message];
                        }

                        if (messages && messages.length > 0) {
                            Ext.Msg.show({
                                title: options.errorMessageTitle || this.title,
                                icon: Ext.MessageBox.ERROR,
                                msg: messages.join(":<br/><br/>- "),
                                buttons: Ext.MessageBox.OK
                            });
                        }
                    }

                    Ext.callback(options.error, options.scope, [ result, options ]);
                    Ext.callback(options._callback, options.scope, [ false, result, options ]);
                }
            }
        }
        else {
            if (options.mask) {
                options.mask.hide();
            }

            Ext.callback(options._callback, options.scope, [ false, null, options ]);
        }
    },


    request: function(o) {

        o._callback = o.callback;
        o.callback = this.defaultAjaxRequestCallback;

        o._success = o.success;
        delete o.success;

        if (o.loadMaskEl || (o.loadMask !== false)) {
            var maskCfg = o.loadMaskCfg || {};
            Ext.applyIf(maskCfg, {
                autoHide: o.autoHideLoadMask !== false
            });
            o.mask = new Ext.LoadMask(o.loadMaskEl || Ext.getBody(), maskCfg);
            o.mask.show();

            delete o.loadMask;
            delete o.loadMaskEl;
            delete o.loadMaskCfg;
            delete o.autoHideLoadMask;
        }

        Ext.applyIf(o, {
            quickMessage: true,
            silent: false
        });

        if (o.errorMessagesOnly) {
            o.silent = true;
            o.showErrorMessages = true;
        }

        return Ext.Ajax.request(o);
    }
});

/**
 * This plugin modifies the default behaviour of buttons: when clicked it
 * will show up a MessageBox with a confirmation message before executing
 * the default handler and firing the 'click' event.
 */
Ext.define('Ext.ux.plugin.ConfirmAction', {
    extend: 'Ext.AbstractPlugin',
    alias: 'plugin.confirmaction',

    /**
     * @cfg {String} confirmationTitle
     * The default title of the confirmation window. Can also be overridden by
     * specifying a config property with the same name on the target button.
     */
    confirmationTitle: 'Confirmation',

    /**
     * @cfg {String} confirmationMessage
     * The default message of the confirmation window. Can also be overridden by
     * specifying a config property with the same name on the target button.
     */
    confirmationMessage: 'Are you sure you want to do this?',

    init: function(button) {
        if (button.fireHandler) {

            var originalHandler = button.fireHandler;
            var confirmationTitle = button.confirmationTitle || this.confirmationTitle;
            var confirmationMessage = button.confirmationMessage || this.confirmationMessage;

            button.fireHandler = function() {
                Ext.MessageBox.confirm(confirmationTitle, confirmationMessage, function(id) {
                    if (id === "yes") {
                        originalHandler.call(this);
                    }
                }, this);
            }
        }
    }
});


/**
 * Container for a group of link buttons. Example usage:
 * <pre><code>
 var p = new Asdp.ActionPanel({
 title: 'Operations',
 items: [{
 text: 'Save',
 iconCls: 'save',
 handler: doSave
 },{
 text: 'Save as...',
 iconCls: 'save-as'
 }]
 });
 * </code></pre>
 */
Ext.define('Ext.ux.ActionPanel', {
    extend: 'Ext.Panel',
    alias: 'widget.actionpanel',

    frame: true,
    collapsible: true,
    cls: 'action-panel',
    autoHeight: true,
    defaultType: 'link'
});

Ext.define('Ext.ux.Link', {
    extend: 'Ext.Component',
    alias: 'widget.link',

    baseCls: Ext.baseCSSPrefix + 'link',
    renderTpl: '<a class="{iconCls}" href="{href}">{text}</a>',

    initComponent: function() {
        var me = this;

        if(me.iconCls){
            me.addClsWithUI("icon");
        }

        me.preventDefault = !me.url;

        me.renderData = {
            text: me.text,
            href: me.url || "#",
            iconCls: me.iconCls
        };

        me.callParent(arguments);

        me.addEvents('click');
    },

    // private
    afterRender: function() {
        this.mon(this.el, 'click', this.onClick, this);
        this.callParent(arguments);
    },

    // private
    onClick: function(e) {
        var me = this;
        if (me.preventDefault && e) {
            e.preventDefault();
        }
        if (e.button !== 0) {
            return;
        }
        me.fireHandler(e);
    },

    fireHandler: function(e){
        var me = this,
            handler = me.handler;

        me.fireEvent('click', me, e);
        if (handler) {
            handler.call(me.scope || me, me, e);
        }
    }
});

Ext.define('Ext.ux.DetailsPanel', {
    extend: 'Ext.Panel',
    alias: 'widget.detailspanel',

    frame: true,
    collapsible: true,
    autoHeight: true,
    cls: 'details-panel',
    title: 'Details',

    /**
     * @cfg {String} summary
     * The summary title.
     */
    summary: '',
    /**
     * @cfg {String/String[]} paragraphs
     * A paragraph or an array of paragraphs.
     */
    paragraphs: '',

    //private
    initComponent: function() {
        this.tpl = new Ext.XTemplate([
            '<div class="details-panel-title">{summary}</div>',
            '<tpl for="paragraphs">',
            '<div class="details-panel-body">{.}</div>',
            '</tpl>'
        ]);

        if (!Ext.isArray(this.paragraphs)) {
            this.paragraphs = [ this.paragraphs ];
        }

        this.callParent();
    },

    // private
    onRender: function() {
        this.callParent(arguments);

        this.tpl.append(this.body, this);
    },

    /**
     * Refresh the view.
     */
    update: function() {
        this.tpl.overwrite(this.body, this);
    }
});

Ext.define('Ext.ux.Timer', {
    extend: 'Ext.Component',
    alias: 'widget.timer',

    renderTpl: '<div class="timer">0:00:00</div>',

    initComponent: function () {

        this.addEvents(
            /**
             * @event timeout
             * Fires when the timer has reached zero.
             */
            'timeout'
        );

        this.runner = new Ext.util.TaskRunner();

        this.callParent();
    },

    startTimer: function (time) {
        this.runner.stopAll();

        this.time = time;

        this.runner.start({
            run: this.onTimerRun,
            interval: 1000,
            scope: this
        });
    },

    onTimerRun: function() {
        var timerEl = Ext.get(Ext.DomQuery.selectNode(".timer", this.el.dom));

        if(timerEl){
            timerEl.update(this.formatTime(this.time--));
        }

        if (this.time < 0) {
            this.fireEvent('timeout');
            // stop the task
            return false;
        }
    },


    formatTime: function (seconds) {

        if (seconds <= 0) {
            return "0:00:00";
        }

        var secs, mins, hours;

        secs = seconds % 60;
        mins = parseInt(seconds / 60);
        hours = parseInt(mins / 60);
        mins = mins % 60;

        var pad = function (str) {
            return Ext.String.leftPad(str, 2, '0');
        };

        return hours + ":" + pad(mins ) + ":" + pad(secs);
    },

    destroy: function () {
        this.runner.stopAll();

        this.callParent(arguments);
    }
});